package builder

import (
	"errors"
	"fmt"
	"strings"
	"yunj/config"
	"yunj/pkg/yunj/core/builder/builderaction"
	"yunj/pkg/yunj/core/builder/builderconsts"
	"yunj/pkg/yunj/core/builder/builderdto"
	"yunj/pkg/yunj/core/builder/buildervalidator"
	"yunj/pkg/yunj/core/builder/form"
	"yunj/pkg/yunj/core/builder/table"
	"yunj/pkg/yunj/core/builder/table/col"
	"yunj/pkg/yunj/core/builder/table/deftoolbar"
	"yunj/pkg/yunj/core/builder/table/toolbar"
	"yunj/pkg/yunj/core/consts"
	errcodeEnum "yunj/pkg/yunj/core/enum/errcode"
	"yunj/pkg/yunj/core/event"
	"yunj/pkg/yunj/core/response"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
	"github.com/worklz/go-validate"
	"golang.org/x/exp/slices"
)

type Table struct {
	Builder
	// 状态栏
	state         []builderdto.TableState
	stateCodes    []any    // 所有的状态栏code切片
	stateCodeStrs []string // 所有的状态栏code字符串值切片
	// 是否开启分页（前端默认true）
	page      bool
	statePage map[any]bool // 状态栏的是否开启分页
	// 主键表头字段
	pk      string
	statePk map[any]string // 状态栏的主键表头字段
	// 标题列
	// 一行数据的标题描述，如：名称、标题等字段。没有设置会优先匹配title、name等，没有的话采用pk
	titleCol      string
	stateTitleCol map[any]string // 状态栏的标题列
	// 每页显示数据条数（默认20）。在page开启时有效
	pageSize      uint
	statePageSize map[any]uint // 状态栏的主键表头字段
	// 每页条数的选择项（默认[10,20,30,40,50,60,70,80,90]）。在page开启时有效
	pageSizeOptions      []uint
	statePageSizeOptions map[any][]uint
	// 筛选表单（默认空）
	filter         []form.FieldInterface // 无状态栏筛选表单
	filterIdx      map[string]int
	stateFilter    map[any][]form.FieldInterface // 状态栏筛选表单
	stateFilterIdx map[any]map[string]int
	// 工具栏（默认空）
	toolbar         []toolbar.ActionInterface // 无状态栏工具栏
	toolbarIdx      map[any]int
	stateToolbar    map[any][]toolbar.ActionInterface // 状态栏工具栏
	stateToolbarIdx map[any]map[any]int
	// 右侧默认工具栏（默认空）
	defaultToolbar         []deftoolbar.ActionInterface // 无状态栏右侧默认工具栏
	defaultToolbarIdx      map[any]int
	stateDefaultToolbar    map[any][]deftoolbar.ActionInterface // 状态栏右侧默认工具栏
	stateDefaultToolbarIdx map[any]map[any]int
	// 是否树形（默认false）
	tree      bool
	stateTree map[any]bool // 状态栏的是否树形
	// 表头
	cols         []table.ColInterface // 无状态栏表头
	colsIdx      map[string]int
	colsMap      map[string]table.ColInterface
	stateCols    map[any][]table.ColInterface // 状态栏表头
	stateColsIdx map[any]map[string]int
	stateColsMap map[any]map[string]table.ColInterface // 状态栏表头map
	// 获取数量的处理方法
	countFunc func(t *Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableCountResult, err error)
	// 获取数据项的处理方法
	itemsFunc func(t *Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableItemsResult, err error)
	// 异步事件的处理方法
	eventFunc func(t *Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableEventResult, err error)
}

// 编译时判断是否实现BuilderInterface接口
var _ BuilderInterface = (*Table)(nil)

// 创建一个新的表格构建器实例
func NewTable(ctx *gin.Context, id string) *Table {
	t := &Table{}
	SetBuilderInstance(&t.Builder, t)
	t.Type = "yunj_table"
	t.Id = id
	t.GinContext = ctx
	t.ActionHandleSort = []string{"State", "Page", "Pk", "TitleCol", "PageSize", "PageSizeOptions", "Filter", "Validator", "Toolbar", "DefaultToolbar", "Tree", "Cols", "Count", "Items", "Event"}
	t.ScriptFileList = []string{util.YunjStaticUrl("/static/yunj/js/table.min.js?v=" + config.VERSION)}
	builderValidator := &buildervalidator.Table{}
	builderValidator.InitValidator(builderValidator)
	t.BuilderValidator = builderValidator
	// 配置默认值
	t.page = true
	t.pk = "id"
	t.pageSize = consts.LIST_PAGE_SIZE
	t.pageSizeOptions = []uint{10, 20, 30, 40, 50, 60, 70, 80, 90}
	return t
}

// 配置表格状态栏
// param: func(t *Table) ([]dto.TableState, error)
// param: []dto.TableState
// param: dto.TableState
func (t *Table) State(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, stateItem := range param {
		if stateFunc, ok := stateItem.(func(t *Table) ([]builderdto.TableState, error)); ok {
			t.addActionHandleFuns("State", stateFunc)
			continue
		}
		if stateItems, ok := stateItem.([]builderdto.TableState); ok {
			t.addActionHandleFuns("State", func(t *Table) ([]builderdto.TableState, error) {
				return stateItems, nil
			})
			continue
		}
		if stateItem, ok := stateItem.(builderdto.TableState); ok {
			t.addActionHandleFuns("State", func(t *Table) ([]builderdto.TableState, error) {
				return []builderdto.TableState{stateItem}, nil
			})
			continue
		}
		t.setError("State 方法传入参数错误")
	}
	return t
}

// 处理表格状态栏的回调方法
func (t *Table) HandleStateFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	stateFunc, ok := fun.(func(t *Table) ([]builderdto.TableState, error))
	if !ok {
		t.setError(errors.New("State 方法传入参数格式错误"))
		return t
	}
	resStates, err := stateFunc(t)
	if err != nil {
		t.setError(err)
		return t
	}
	if len(resStates) > 0 {
		currStates := t.state
		t.state = append(currStates, resStates...)
	}
	for i, state := range t.state {
		if state.Code == nil {
			t.setError(fmt.Errorf("State 方法设置索引为%d的状态Code值不能为nil", i))
			return t
		}
	}
	return t
}

// 配置表格是否开启分页
// param: func(t *Table, state *dto.TableState) (bool, error)
// param: bool
func (t *Table) Page(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) (bool, error)); ok {
			t.addActionHandleFuns("Page", fun)
			continue
		}
		if itemValue, ok := item.(bool); ok {
			t.addActionHandleFuns("Page", func(t *Table, state *builderdto.TableState) (bool, error) {
				return itemValue, nil
			})
		}
	}
	return t
}

// 处理表格是否开启分页的回调方法
func (t *Table) HandlePageFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	handle, ok := fun.(func(t *Table, state *builderdto.TableState) (bool, error))
	if !ok {
		t.setError(errors.New("Page 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.statePage == nil {
			t.statePage = map[any]bool{}
		}
		for _, state := range t.state {
			resPage, err := handle(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			t.statePage[state.Code] = resPage
		}
	} else {
		resPage, err := handle(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		t.page = resPage
	}
	return t
}

// 配置表格主键表头字段
// param: func(t *Table, state *dto.TableState) (string, error)
// param: string
func (t *Table) Pk(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) (string, error)); ok {
			t.addActionHandleFuns("Pk", fun)
			continue
		}
		if itemValue, ok := item.(string); ok {
			t.addActionHandleFuns("Pk", func(t *Table, state *builderdto.TableState) (string, error) {
				return itemValue, nil
			})
		}
	}
	return t
}

// 处理表格主键表头字段的回调方法
func (t *Table) HandlePkFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	handle, ok := fun.(func(t *Table, state *builderdto.TableState) (string, error))
	if !ok {
		t.setError(errors.New("Pk 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.statePk == nil {
			t.statePk = map[any]string{}
		}
		for _, state := range t.state {
			resPk, err := handle(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			t.statePk[state.Code] = resPk
		}
	} else {
		resPk, err := handle(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		t.pk = resPk
	}
	return t
}

// 配置表格标题列
// 一行数据的标题描述，如：名称、标题等字段。没有设置会优先匹配title、name等，没有的话采用pk
// param: func(t *Table, state *dto.TableState) (string, error)
// param: string
func (t *Table) TitleCol(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) (string, error)); ok {
			t.addActionHandleFuns("TitleCol", fun)
			continue
		}
		if itemValue, ok := item.(string); ok {
			t.addActionHandleFuns("TitleCol", func(t *Table, state *builderdto.TableState) (string, error) {
				return itemValue, nil
			})
		}
	}
	return t
}

// 处理表格标题列的回调方法
func (t *Table) HandleTitleColFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	handle, ok := fun.(func(t *Table, state *builderdto.TableState) (string, error))
	if !ok {
		t.setError(errors.New("TitleCol 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.stateTitleCol == nil {
			t.stateTitleCol = map[any]string{}
		}
		for _, state := range t.state {
			resTitleCol, err := handle(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			t.stateTitleCol[state.Code] = resTitleCol
		}
	} else {
		resTitleCol, err := handle(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		t.titleCol = resTitleCol
	}
	return t
}

// 配置每页数据条数
// param: func(t *Table, state *dto.TableState) (uint, error)
// param: uint
func (t *Table) PageSize(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) (uint, error)); ok {
			t.addActionHandleFuns("PageSize", fun)
			continue
		}
		if itemValue, ok := item.(uint); ok {
			t.addActionHandleFuns("PageSize", func(t *Table, state *builderdto.TableState) (uint, error) {
				return itemValue, nil
			})
		}
	}
	return t
}

// 处理表格每页数据条数的回调方法
func (t *Table) HandlePageSizeFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	handle, ok := fun.(func(t *Table, state *builderdto.TableState) (uint, error))
	if !ok {
		t.setError(errors.New("PageSize 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.statePageSize == nil {
			t.statePageSize = map[any]uint{}
		}
		for _, state := range t.state {
			resPageSize, err := handle(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			t.statePageSize[state.Code] = resPageSize
		}
	} else {
		resPageSize, err := handle(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		t.pageSize = resPageSize
	}
	return t
}

// 配置每页条数的选择项
// param: func(t *Table, state *dto.TableState) ([]uint, error)
// param: []uint
func (t *Table) PageSizeOptions(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) ([]uint, error)); ok {
			t.addActionHandleFuns("PageSize", fun)
			continue
		}
		if itemValue, ok := item.([]uint); ok {
			t.addActionHandleFuns("PageSize", func(t *Table, state *builderdto.TableState) ([]uint, error) {
				return itemValue, nil
			})
		}
	}
	return t
}

// 处理表格每页条数的选择项的回调方法
func (t *Table) HandlePageSizeOptionsFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	handle, ok := fun.(func(t *Table, state *builderdto.TableState) ([]uint, error))
	if !ok {
		t.setError(errors.New("PageSizeOptions 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.statePageSizeOptions == nil {
			t.statePageSizeOptions = map[any][]uint{}
		}
		for _, state := range t.state {
			resPageSizeOptions, err := handle(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			t.statePageSizeOptions[state.Code] = resPageSizeOptions
		}
	} else {
		resPageSizeOptions, err := handle(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		t.pageSizeOptions = resPageSizeOptions
	}
	return t
}

// 配置筛选表单
// param: func(t *Table, state *dto.TableState) ([]form.FieldInterface, error)
// param: []form.FieldInterface
// param: form.FieldInterface
func (t *Table) Filter(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) ([]form.FieldInterface, error)); ok {
			t.addActionHandleFuns("Filter", fun)
			continue
		}
		if itemsValue, ok := item.([]form.FieldInterface); ok {
			t.addActionHandleFuns("Filter", func(t *Table, state *builderdto.TableState) ([]form.FieldInterface, error) {
				return itemsValue, nil
			})
			continue
		}
		if itemValue, ok := item.(form.FieldInterface); ok {
			t.addActionHandleFuns("Filter", func(t *Table, state *builderdto.TableState) ([]form.FieldInterface, error) {
				return []form.FieldInterface{itemValue}, nil
			})
			continue
		}
	}
	return t
}

// 处理筛选表单的回调方法
func (t *Table) HandleFilterFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	filterFunc, ok := fun.(func(t *Table, state *builderdto.TableState) ([]form.FieldInterface, error))
	if !ok {
		t.setError(errors.New("Filter 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.stateFilter == nil {
			t.stateFilter = map[any][]form.FieldInterface{}
		}
		if t.stateFilterIdx == nil {
			t.stateFilterIdx = map[any]map[string]int{}
		}
		for _, state := range t.state {
			resFilter, err := filterFunc(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			err = t.handleFilterFields(resFilter, &state)
			if err != nil {
				t.setError(err)
				return t
			}
		}
	} else {
		resFilter, err := filterFunc(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		err = t.handleFilterFields(resFilter, nil)
		if err != nil {
			t.setError(err)
			return t
		}
	}
	return t
}

// 处理筛选表单字段
func (t *Table) handleFilterFields(fields []form.FieldInterface, state *builderdto.TableState) (err error) {
	var hasAuth bool
	var tableFilter []form.FieldInterface
	var tableFilterIdx map[string]int
	if state == nil {
		tableFilter = t.filter
		tableFilterIdx = t.filterIdx
	} else {
		if t.stateFilter == nil {
			t.stateFilter = map[any][]form.FieldInterface{}
		}
		if t.stateFilterIdx == nil {
			t.stateFilterIdx = map[any]map[string]int{}
		}
		var ok bool
		tableFilter, ok = t.stateFilter[state.Code]
		if !ok {
			tableFilter = []form.FieldInterface{}
		}
		tableFilterIdx, ok = t.stateFilterIdx[state.Code]
		if !ok {
			tableFilterIdx = map[string]int{}
		}
	}
	if tableFilter == nil || len(tableFilter) <= 0 {
		tableFilter = []form.FieldInterface{}
	}
	if tableFilterIdx == nil {
		tableFilterIdx = map[string]int{}
	}
	formId, err := t.GetId()
	if err != nil {
		return
	}
	if state != nil {
		formId += fmt.Sprintf("_%s", state.Code)
	}
	for _, filterField := range fields {
		hasAuth, err = filterField.RenderHandle(t.GinContext, formId)
		if err != nil {
			return
		}
		// 没有权限
		if !hasAuth {
			continue
		}
		id, _ := filterField.GetFieldId()
		// 判断原来是否存在
		idx, exists := tableFilterIdx[id]
		if exists {
			tableFilter[idx] = filterField
		} else {
			tableFilter = append(tableFilter, filterField)
			tableFilterIdx[id] = len(tableFilter) - 1
		}
	}
	if state == nil {
		t.filter = tableFilter
		t.filterIdx = tableFilterIdx
	} else {
		if t.stateFilter == nil {
			t.stateFilter = map[any][]form.FieldInterface{}
		}
		if t.stateFilterIdx == nil {
			t.stateFilterIdx = map[any]map[string]int{}
		}
		t.stateFilter[state.Code] = tableFilter
		t.stateFilterIdx[state.Code] = tableFilterIdx
	}
	return
}

// 配置验证器
func (t *Table) Validator(param any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	if fun, ok := param.(func(t *Table) (validate.ValidatorInterface, error)); ok {
		t.addActionHandleFuns("Validator", fun)
		return t
	}
	if validator, ok := param.(validate.ValidatorInterface); ok {
		t.addActionHandleFuns("Validator", func(t *Table) (validate.ValidatorInterface, error) {
			return validator, nil
		})
	}
	return t
}

// 处理表格验证器的回调方法
func (t *Table) HandleValidatorFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	validatorFun, ok := fun.(func(t *Table) (validate.ValidatorInterface, error))
	if !ok {
		t.setError(errors.New("Validator 方法传入参数格式错误"))
		return t
	}
	validator, err := validatorFun(t)
	if err != nil {
		t.setError(err)
		return t
	}
	t.ValidatorInstance = validator
	return t
}

// 配置工具栏
// param: func(t *Table, state *dto.TableState) ([]toolbar.ActionInterface, error)
// param: []toolbar.ActionInterface
// param: toolbar.ActionInterface
func (t *Table) Toolbar(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) ([]toolbar.ActionInterface, error)); ok {
			t.addActionHandleFuns("Toolbar", fun)
			continue
		}
		if itemsValue, ok := item.([]toolbar.ActionInterface); ok {
			t.addActionHandleFuns("Toolbar", func(t *Table, state *builderdto.TableState) ([]toolbar.ActionInterface, error) {
				return itemsValue, nil
			})
		}
		if itemValue, ok := item.(toolbar.ActionInterface); ok {
			t.addActionHandleFuns("Toolbar", func(t *Table, state *builderdto.TableState) ([]toolbar.ActionInterface, error) {
				return []toolbar.ActionInterface{itemValue}, nil
			})
		}
	}
	return t
}

// 处理工具栏的回调方法
func (t *Table) HandleToolbarFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	toolbarFunc, ok := fun.(func(t *Table, state *builderdto.TableState) ([]toolbar.ActionInterface, error))
	if !ok {
		t.setError(errors.New("Toolbar 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.stateToolbar == nil {
			t.stateToolbar = map[any][]toolbar.ActionInterface{}
		}
		if t.stateToolbarIdx == nil {
			t.stateToolbarIdx = map[any]map[any]int{}
		}
		for _, state := range t.state {
			resToolbar, err := toolbarFunc(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			err = t.handleToolbarItems(resToolbar, &state)
			if err != nil {
				t.setError(err)
				return t
			}
		}
	} else {
		resToolbar, err := toolbarFunc(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		err = t.handleToolbarItems(resToolbar, nil)
		if err != nil {
			t.setError(err)
			return t
		}
	}
	return t
}

// 处理工具栏项
func (t *Table) handleToolbarItems(toolbars []toolbar.ActionInterface, state *builderdto.TableState) (err error) {
	var hasAuth bool
	var tableToolbar []toolbar.ActionInterface
	var tableToolbarIdx map[any]int
	if state == nil {
		tableToolbar = t.toolbar
		tableToolbarIdx = t.toolbarIdx
	} else {
		if t.stateToolbar == nil {
			t.stateToolbar = map[any][]toolbar.ActionInterface{}
		}
		if t.stateToolbarIdx == nil {
			t.stateToolbarIdx = map[any]map[any]int{}
		}
		var ok bool
		tableToolbar, ok = t.stateToolbar[state.Code]
		if !ok {
			tableToolbar = []toolbar.ActionInterface{}
		}
		tableToolbarIdx, ok = t.stateToolbarIdx[state.Code]
		if !ok {
			tableToolbarIdx = map[any]int{}
		}
	}
	if tableToolbar == nil || len(tableToolbar) <= 0 {
		tableToolbar = []toolbar.ActionInterface{}
	}
	if tableToolbarIdx == nil {
		tableToolbarIdx = map[any]int{}
	}
	for _, toolbar := range toolbars {
		hasAuth, err = toolbar.RenderHandle(t.GinContext, t.Id)
		if err != nil {
			return
		}
		// 没有权限
		if !hasAuth {
			continue
		}
		code, _ := toolbar.GetActionCode()
		// 判断原来是否存在
		idx, exists := tableToolbarIdx[code]
		if exists {
			tableToolbar[idx] = toolbar
		} else {
			tableToolbar = append(tableToolbar, toolbar)
			tableToolbarIdx[code] = len(tableToolbar) - 1
		}
	}
	if state == nil {
		t.toolbar = tableToolbar
		t.toolbarIdx = tableToolbarIdx
	} else {
		if t.stateToolbar == nil {
			t.stateToolbar = map[any][]toolbar.ActionInterface{}
		}
		if t.stateToolbarIdx == nil {
			t.stateToolbarIdx = map[any]map[any]int{}
		}
		t.stateToolbar[state.Code] = tableToolbar
		t.stateToolbarIdx[state.Code] = tableToolbarIdx
	}
	return
}

// 配置右侧默认工具栏
// param: func(t *Table, state *dto.TableState) ([]deftoolbar.ActionInterface, error)
// param: []deftoolbar.ActionInterface
// param: deftoolbar.ActionInterface
func (t *Table) DefaultToolbar(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) ([]deftoolbar.ActionInterface, error)); ok {
			t.addActionHandleFuns("DefaultToolbar", fun)
			continue
		}
		if itemsValue, ok := item.([]deftoolbar.ActionInterface); ok {
			t.addActionHandleFuns("DefaultToolbar", func(t *Table, state *builderdto.TableState) ([]deftoolbar.ActionInterface, error) {
				return itemsValue, nil
			})
		}
		if itemValue, ok := item.(deftoolbar.ActionInterface); ok {
			t.addActionHandleFuns("DefaultToolbar", func(t *Table, state *builderdto.TableState) ([]deftoolbar.ActionInterface, error) {
				return []deftoolbar.ActionInterface{itemValue}, nil
			})
		}
	}
	return t
}

// 处理右侧默认工具栏的回调方法
func (t *Table) HandleDefaultToolbarFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	toolbarFunc, ok := fun.(func(t *Table, state *builderdto.TableState) ([]deftoolbar.ActionInterface, error))
	if !ok {
		t.setError(errors.New("DefaultToolbar 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.stateDefaultToolbar == nil {
			t.stateDefaultToolbar = map[any][]deftoolbar.ActionInterface{}
		}
		if t.stateDefaultToolbarIdx == nil {
			t.stateDefaultToolbarIdx = map[any]map[any]int{}
		}
		for _, state := range t.state {
			resDefaultToolbar, err := toolbarFunc(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			err = t.handleDefaultToolbarItems(resDefaultToolbar, &state)
			if err != nil {
				t.setError(err)
				return t
			}
		}
	} else {
		resDefaultToolbar, err := toolbarFunc(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		err = t.handleDefaultToolbarItems(resDefaultToolbar, nil)
		if err != nil {
			t.setError(err)
			return t
		}
	}
	return t
}

// 处理右侧默认工具栏项
func (t *Table) handleDefaultToolbarItems(toolbars []deftoolbar.ActionInterface, state *builderdto.TableState) (err error) {
	var hasAuth bool
	var tableDefaultToolbar []deftoolbar.ActionInterface
	var tableDefaultToolbarIdx map[any]int
	if state == nil {
		tableDefaultToolbar = t.defaultToolbar
		tableDefaultToolbarIdx = t.defaultToolbarIdx
	} else {
		if t.stateDefaultToolbar == nil {
			t.stateDefaultToolbar = map[any][]deftoolbar.ActionInterface{}
		}
		if t.stateDefaultToolbarIdx == nil {
			t.stateDefaultToolbarIdx = map[any]map[any]int{}
		}
		var ok bool
		tableDefaultToolbar, ok = t.stateDefaultToolbar[state.Code]
		if !ok {
			tableDefaultToolbar = []deftoolbar.ActionInterface{}
		}
		tableDefaultToolbarIdx, ok = t.stateDefaultToolbarIdx[state.Code]
		if !ok {
			tableDefaultToolbarIdx = map[any]int{}
		}
	}
	if tableDefaultToolbar == nil || len(tableDefaultToolbar) <= 0 {
		tableDefaultToolbar = []deftoolbar.ActionInterface{}
	}
	if tableDefaultToolbarIdx == nil {
		tableDefaultToolbarIdx = map[any]int{}
	}
	for _, toolbar := range toolbars {
		hasAuth, err = toolbar.RenderHandle(t.GinContext, t.Id)
		if err != nil {
			return
		}
		// 没有权限
		if !hasAuth {
			continue
		}
		code, _ := toolbar.GetActionCode()
		// 判断原来是否存在
		idx, exists := tableDefaultToolbarIdx[code]
		if exists {
			tableDefaultToolbar[idx] = toolbar
		} else {
			tableDefaultToolbar = append(tableDefaultToolbar, toolbar)
			tableDefaultToolbarIdx[code] = len(tableDefaultToolbar) - 1
		}
	}
	if state == nil {
		t.defaultToolbar = tableDefaultToolbar
		t.defaultToolbarIdx = tableDefaultToolbarIdx
	} else {
		if t.stateDefaultToolbar == nil {
			t.stateDefaultToolbar = map[any][]deftoolbar.ActionInterface{}
		}
		if t.stateDefaultToolbarIdx == nil {
			t.stateDefaultToolbarIdx = map[any]map[any]int{}
		}
		t.stateDefaultToolbar[state.Code] = tableDefaultToolbar
		t.stateDefaultToolbarIdx[state.Code] = tableDefaultToolbarIdx
	}
	return
}

// 配置表格是否树形
// param: func(t *Table, state *dto.TableState) (bool, error)
// param: bool
func (t *Table) Tree(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) (bool, error)); ok {
			t.addActionHandleFuns("Tree", fun)
			continue
		}
		if itemValue, ok := item.(bool); ok {
			t.addActionHandleFuns("Tree", func(t *Table, state *builderdto.TableState) (bool, error) {
				return itemValue, nil
			})
		}
	}
	return t
}

// 处理表格是否树形的回调方法
func (t *Table) HandleTreeFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	handle, ok := fun.(func(t *Table, state *builderdto.TableState) (bool, error))
	if !ok {
		t.setError(errors.New("Tree 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.stateTree == nil {
			t.stateTree = map[any]bool{}
		}
		for _, state := range t.state {
			resTree, err := handle(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			t.stateTree[state.Code] = resTree
		}
	} else {
		resTree, err := handle(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		t.tree = resTree
	}
	return t
}

// 配置表头
// param: func(t *Table, state *dto.TableState) ([]table.ColInterface, error)
// param: []table.ColInterface
// param: table.ColInterface
func (t *Table) Cols(param ...any) *Table {
	if param == nil {
		return t
	}
	if err := t.GetError(); err != nil {
		return t
	}
	for _, item := range param {
		if fun, ok := item.(func(t *Table, state *builderdto.TableState) ([]table.ColInterface, error)); ok {
			t.addActionHandleFuns("Cols", fun)
			continue
		}
		if itemsValue, ok := item.([]table.ColInterface); ok {
			t.addActionHandleFuns("Cols", func(t *Table, state *builderdto.TableState) ([]table.ColInterface, error) {
				return itemsValue, nil
			})
		}
		if itemValue, ok := item.(table.ColInterface); ok {
			t.addActionHandleFuns("Cols", func(t *Table, state *builderdto.TableState) ([]table.ColInterface, error) {
				return []table.ColInterface{itemValue}, nil
			})
		}
	}
	return t
}

// 处理表头的回调方法
func (t *Table) HandleColsFunc(fun any) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	filterFunc, ok := fun.(func(t *Table, state *builderdto.TableState) ([]table.ColInterface, error))
	if !ok {
		t.setError(errors.New("Cols 方法传入参数格式错误"))
		return t
	}
	if t.IsSetState() {
		if t.stateCols == nil {
			t.stateCols = map[any][]table.ColInterface{}
		}
		if t.stateColsIdx == nil {
			t.stateColsIdx = map[any]map[string]int{}
		}
		for _, state := range t.state {
			resCols, err := filterFunc(t, &state)
			if err != nil {
				t.setError(err)
				return t
			}
			err = t.handleColItems(resCols, &state)
			if err != nil {
				t.setError(err)
				return t
			}
		}
	} else {
		resCols, err := filterFunc(t, nil)
		if err != nil {
			t.setError(err)
			return t
		}
		err = t.handleColItems(resCols, nil)
		if err != nil {
			t.setError(err)
			return t
		}
	}
	return t
}

// 处理表头项
func (t *Table) handleColItems(cols []table.ColInterface, state *builderdto.TableState) (err error) {
	var hasAuth bool
	var tableCols []table.ColInterface
	var tableColsIdx map[string]int
	if state == nil {
		tableCols = t.cols
		tableColsIdx = t.colsIdx
	} else {
		if t.stateCols == nil {
			t.stateCols = map[any][]table.ColInterface{}
		}
		if t.stateColsIdx == nil {
			t.stateColsIdx = map[any]map[string]int{}
		}
		var ok bool
		tableCols, ok = t.stateCols[state.Code]
		if !ok {
			tableCols = []table.ColInterface{}
		}
		tableColsIdx, ok = t.stateColsIdx[state.Code]
		if !ok {
			tableColsIdx = map[string]int{}
		}
	}
	if tableCols == nil || len(tableCols) <= 0 {
		tableCols = []table.ColInterface{}
	}
	if tableColsIdx == nil {
		tableColsIdx = map[string]int{}
	}
	for _, col := range cols {
		hasAuth, err = col.RenderHandle(t.GinContext, t.Id)
		if err != nil {
			return
		}
		// 没有权限
		if !hasAuth {
			continue
		}
		colField, _ := col.GetColField()
		// 判断原来是否存在
		idx, exists := tableColsIdx[colField]
		if exists {
			tableCols[idx] = col
		} else {
			tableCols = append(tableCols, col)
			tableColsIdx[colField] = len(tableCols) - 1
		}
	}
	if state == nil {
		t.cols = tableCols
		t.colsIdx = tableColsIdx
	} else {
		if t.stateCols == nil {
			t.stateCols = map[any][]table.ColInterface{}
		}
		if t.stateColsIdx == nil {
			t.stateColsIdx = map[any]map[string]int{}
		}
		t.stateCols[state.Code] = tableCols
		t.stateColsIdx[state.Code] = tableColsIdx
	}
	return
}

// 配置表格数量获取的处理方法
func (t *Table) Count(fun func(t *Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableCountResult, err error)) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	t.countFunc = fun
	return t
}

// 配置表格数据项获取的处理方法
func (t *Table) Items(fun func(t *Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableItemsResult, err error)) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	t.itemsFunc = fun
	return t
}

// 配置表格事件的处理方法
func (t *Table) Event(fun func(t *Table, requestParam *builderdto.TableRequestParam) (res builderdto.TableEventResult, err error)) *Table {
	if err := t.GetError(); err != nil {
		return t
	}
	t.eventFunc = fun
	return t
}

// 视图模板配置数据
func (t *Table) viewArgs() (args map[string]any) {
	args = t.Builder.viewArgs()
	if len(t.state) > 0 {
		args["state"] = t.state
	}
	if t.stateFilter != nil {
		args["filter"] = t.stateFilter
	} else if len(t.filter) > 0 {
		args["filter"] = t.filter
	}
	hasCols := false
	if t.stateCols != nil {
		args["cols"] = t.stateCols
		hasCols = true
	} else if len(t.cols) > 0 {
		args["cols"] = t.cols
		hasCols = true
	}
	if hasCols {
		if t.statePage != nil {
			args["page"] = t.statePage
		} else {
			args["page"] = t.page
		}
		if t.statePageSize != nil {
			args["pageSize"] = t.statePageSize
		} else {
			args["pageSize"] = t.pageSize
		}
		if t.statePageSizeOptions != nil {
			args["pageSizeOptions"] = t.statePageSizeOptions
		} else {
			args["pageSizeOptions"] = t.pageSizeOptions
		}
		if t.statePk != nil {
			args["pk"] = t.statePk
		} else {
			args["pk"] = t.pk
		}
		if t.stateTitleCol != nil {
			args["titleCol"] = t.stateTitleCol
		} else {
			args["titleCol"] = t.titleCol
		}
		if t.stateToolbar != nil {
			args["toolbar"] = t.stateToolbar
		} else {
			args["toolbar"] = t.toolbar
		}
		if t.stateDefaultToolbar != nil {
			args["defaultToolbar"] = t.stateDefaultToolbar
		} else {
			args["defaultToolbar"] = t.defaultToolbar
		}
		if t.stateTree != nil {
			args["tree"] = t.stateTree
		} else {
			args["tree"] = t.tree
		}
	}
	if err := t.GetError(); err != nil {
		ctx := t.GetGinContext()
		util.RedirectAdminTips(ctx, errcodeEnum.ERROR, err.Error())
	}

	return
}

// 获取配置主键
func (t *Table) GetPk(stateCode any) (pk string, err error) {
	if err = t.GetError(); err != nil {
		return
	}
	t.handleActionFuns("State", "Pk")
	if t.statePk != nil {
		pk, _ = tableMapStateValue(stateCode, t.statePk)
	} else {
		pk = t.pk
	}
	if pk == "" {
		err = errors.New("主键Pk未配置")
	}
	return
}

// 异步处理前执行
func (t *Table) BeforeHandleAsync(params map[string]any) (err error) {
	// 事件验证
	if t.ValidatorInstance != nil {
		err = t.ValidatorInstance.SetDatas(params)
		if err != nil {
			err = fmt.Errorf("事件验证器验证参数设置异常！%v", err)
			return
		}
		err = t.ValidatorInstance.CheckScene("Table" + params["builder_async_type"].(string))
		if err != nil {
			response.FailJsonData(err.Error()).AbortResponse(t.GinContext)
			return
		}
		params, err = t.ValidatorInstance.GetDatas()
		if err != nil {
			err = fmt.Errorf("事件验证器请求数据获取异常！%v", err)
			return
		}
	}
	return
}

// 获取请求数据
func (t *Table) getRequestParam(params map[string]any, scene string) (requestParam *builderdto.TableRequestParam, err error) {
	requestParam = &builderdto.TableRequestParam{}
	err = util.MapToStruct(params, requestParam)
	if err != nil {
		err = fmt.Errorf("表格构建器获取获取请求数据异常！%v", err)
		return
	}
	// state
	var stateCode any
	if t.IsSetState() {
		if requestParam.State == nil {
			err = errors.New("state参数缺失")
			return
		}
		stateCode = requestParam.State
		var stateStr string
		stateStr, err = util.ToString(stateCode)
		if err != nil {
			err = fmt.Errorf("state参数非比较类型！%v", err)
			return
		}
		stateCodeStrs := t.GetStateCodeStrs()
		if !slices.Contains(stateCodeStrs, stateStr) {
			err = errors.New("state参数错误")
			return
		}
	}
	// 事件验证
	if requestParam.EventCode != nil {
		// location验证
		err = validate.CheckVar(
			requestParam.EventLocation,
			fmt.Sprintf("required|in:%s,%s,%s", builderconsts.TABLE_EVENT_LOCATION_TOOLBAR, builderconsts.TABLE_EVENT_LOCATION_DEFAULT_TOOLBAR, builderconsts.TABLE_EVENT_LOCATION_COLUMN),
			"事件发生位置",
			nil,
		)
		if err != nil {
			return
		}

		// code验证
		var eventCodeStrs []string
		eventCodes := t.GetEventCodes(stateCode, requestParam.EventLocation)
		for _, eventCode := range eventCodes {
			eventCodeStrs = append(eventCodeStrs, fmt.Sprintf("%v", eventCode))
		}
		err = validate.CheckVar(
			requestParam.EventCode,
			"required|in:"+strings.Join(eventCodeStrs, ","),
			"事件code",
			nil,
		)
		if err != nil {
			return
		}
		// confirm_form_data
		if requestParam.EventConfirmFormData != nil {
			confirmFormFields := t.GetConfirmFormFields(requestParam.State, requestParam.EventLocation, requestParam.EventCode)
			if err = t.CheckFormFields(requestParam.EventConfirmFormData, confirmFormFields, scene+"ConfirmForm"); err != nil {
				err = fmt.Errorf("事件确认表单参数错误！%v", err)
				return
			}
		}
	}
	// filter
	if t.IsSetFilter() {
		var filterFields []form.FieldInterface
		if t.IsSetState() {
			filterFields, _ = tableMapStateValue(stateCode, t.stateFilter)
		} else {
			filterFields = t.filter
		}
		if len(filterFields) > 0 {
			if err = t.CheckFormFields(requestParam.FilterData(), filterFields, scene+"Filter"); err != nil {
				return
			}
		}
	}
	// 是否启用分页
	isEnablePage := t.IsEnablePage(stateCode)
	// page_size
	if isEnablePage && requestParam.PageSize > 0 {
		pageSize := uint(requestParam.PageSize)
		// 判断是否为导出
		if t.IsRequestExportItems() && pageSize == builderconsts.TABLE_BUILDER_EXPORT_API_SINGLE_LIMIT {
			if pageSize != builderconsts.TABLE_BUILDER_EXPORT_API_SINGLE_LIMIT {
				err = fmt.Errorf("page_size参数错误，导出单次请求最大数量：%v，给定值：%v", builderconsts.TABLE_BUILDER_EXPORT_API_SINGLE_LIMIT, pageSize)
				return
			}
		} else {
			var exists bool
			pageSizeOptions := t.GetPageSizeOptionsByState(stateCode)
			for _, pageSizeOption := range pageSizeOptions {
				if pageSize == pageSizeOption {
					exists = true
					break
				}
			}
			if !exists {
				err = fmt.Errorf("page_size参数错误，合法范围：%v，给定值：%v", pageSizeOptions, pageSize)
				return
			}
		}
	}
	// sort
	if requestParam.Sort != nil {
		var colFields []string
		colFields, err = t.getColFields(stateCode)
		if err != nil {
			return
		}
		requestParam.Sort.InitValidator(requestParam.Sort)
		requestParam.Sort.SetRules(map[string]interface{}{
			"field": "required|in:" + strings.Join(colFields, ","),
		})
		err = requestParam.Sort.Check()
		if err != nil {
			err = fmt.Errorf("排序参数错误！%v", err)
			return
		}
	}
	// export
	if requestParam.Export != nil {
		var allowFields []string
		allowFields, err = t.getExportAllowFields(stateCode)
		if err != nil {
			err = fmt.Errorf("导出异常！%v", err)
			return
		}
		requestParam.Export.InitValidator(requestParam.Export)
		requestParam.Export.SetRules(map[string]interface{}{
			"fields": "required|arrayIn:" + strings.Join(allowFields, ","),
		})
		err = requestParam.Export.Check()
		if err != nil {
			err = fmt.Errorf("导出参数错误！%v", err)
			return
		}
		// 是否启用分页
		requestParam.Export.IsEnablePage = isEnablePage
	}
	return
}

// 处理异步状态数量获取
func (t *Table) HandleAsyncStateCount(params map[string]any) *response.JsonData {
	if t.countFunc == nil {
		return response.FailJsonData("表格获取数量的处理方法Count未设置")
	}
	t.handleActionFuns("State", "Filter")
	if len(t.state) <= 0 {
		return response.FailJsonData("表格State未设置")
	}
	res := map[any]int64{}
	for _, state := range t.state {
		requestParam := &builderdto.TableRequestParam{State: state.Code, Pks: []any{}, Filter: ""}
		stateRes, err := t.countFunc(t, requestParam)
		if err != nil {
			return response.FailJsonData(err.Error())
		}
		res[state.Code] = stateRes.Count
	}
	return response.SuccessJsonData(res)
}

// 处理异步数量获取
func (t *Table) HandleAsyncCount(params map[string]any) *response.JsonData {
	if t.countFunc == nil {
		return response.FailJsonData("表格获取数量的处理方法Count未设置")
	}
	requestParam, err := t.getRequestParam(params, "TableCount")
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	res, err := t.countFunc(t, requestParam)
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	return response.SuccessJsonData(res)
}

// 处理异步数据项获取
func (t *Table) HandleAsyncItems(params map[string]any) *response.JsonData {
	if t.itemsFunc == nil {
		return response.FailJsonData("表格获取数量的处理方法Items未设置")
	}
	requestParam, err := t.getRequestParam(params, "TableItems")
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	res, err := t.itemsFunc(t, requestParam)
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	// 判断是否请求导出items
	if t.IsRequestExportItems() {
		// 获取导出items数据，导出值输出替换
		res.Items, err = t.getExportItems(requestParam.State, res.Items)
		if err != nil {
			return response.FailJsonData(err.Error())
		}
	}
	return response.SuccessJsonData(res)
}

// 获取导出items数据，导出值输出替换
func (t *Table) getExportItems(stateCode any, items any) (newItems []map[string]any, err error) {
	itemsJson, err := util.ToJson(items)
	if err != nil {
		err = fmt.Errorf("表格构建器获取导出请求数据json转换异常！%v", err)
		return
	}
	newItems, err = util.JsonTo[[]map[string]any](itemsJson)
	if err != nil {
		err = fmt.Errorf("表格构建器获取导出请求数据json转换map切片异常！%v", err)
		return
	}
	var col table.ColInterface
	for _, item := range newItems {
		for k, v := range item {
			col, err = t.getCol(stateCode, k)
			if err != nil {
				return
			}
			if col != nil {
				item[k] = col.GetExportValue(v) // 获取导出值
			}
		}
	}
	return
}

// 异步事件处理前的事件数据
type TableEventHandleBeforeEventData struct {
	Table        *Table
	RequestParam *builderdto.TableRequestParam
}

// 处理异步事件处理
func (t *Table) HandleAsyncEvent(params map[string]any) *response.JsonData {
	if t.eventFunc == nil {
		return response.FailJsonData("表格事件的处理方法Event未设置")
	}
	requestParam, err := t.getRequestParam(params, "TableEvent")
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	// 触发表格构建器导出任务事件
	err = event.Publish("table.builder.event.before", TableEventHandleBeforeEventData{
		Table:        t,
		RequestParam: requestParam,
	})
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	res, err := t.eventFunc(t, requestParam)
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	if res.ResponseJsonData != nil {
		return res.ResponseJsonData
	}
	return response.SuccessJsonData(res, res.Message)
}

// 导出任务事件数据
type TableExportTaskEventData struct {
	Table        *Table
	TaskId       uint64
	RequestParam *builderdto.TableRequestParam
}

// 处理异步导出任务
func (t *Table) HandleAsyncExport(params map[string]any) *response.JsonData {
	requestParam, err := t.getRequestParam(params, "TableExport")
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	// 创建任务数据...
	taskId, err := util.SnowflakeId()
	if err != nil {
		return response.FailJsonData(fmt.Sprintf("导出任务id生成异常！%v", err))
	}
	// 触发表格构建器导出任务事件
	err = event.Publish("table.builder.export.task", TableExportTaskEventData{
		Table:        t,
		TaskId:       taskId,
		RequestParam: requestParam,
	})
	if err != nil {
		return response.FailJsonData(err.Error())
	}
	return response.SuccessJsonData(nil, "导出任务创建成功，详情请查看任务中心或关注站点消息通知！")
}

// 获取导出允许的字段
func (t *Table) getExportAllowFields(stateCode any) (fields []string, err error) {
	t.handleActionFuns("State", "Cols", "DefaultToolbar")
	if err = t.GetError(); err != nil {
		return
	}
	// 默认工具栏中定义的导出字段
	var defaultToolbar []deftoolbar.ActionInterface
	if t.IsSetState() {
		if t.stateDefaultToolbar != nil {
			defaultToolbar, _ = tableMapStateValue(stateCode, t.stateDefaultToolbar)
		}
	} else {
		defaultToolbar = t.defaultToolbar
	}
	for _, dt := range defaultToolbar {
		dtExport, ok := dt.(*deftoolbar.Export)
		if !ok {
			continue
		}
		if len(dtExport.Fields) > 0 {
			for _, field := range dtExport.Fields {
				if field.Field == "" {
					continue
				}
				fields = append(fields, field.Field)
			}
			if len(fields) > 0 {
				return
			}
		}
		break
	}
	// 表头中定义的字段
	fields, err = t.getColFields(stateCode)
	return
}

// 获取表头中定义的字段
func (t *Table) getColFields(stateCode any) (fields []string, err error) {
	t.handleActionFuns("State", "Cols")
	if err = t.GetError(); err != nil {
		return
	}
	// 表头中定义的字段
	var cols []table.ColInterface
	if t.IsSetState() {
		if t.stateCols != nil {
			cols, _ = tableMapStateValue(stateCode, t.stateCols)
		}
	} else {
		cols = t.cols
	}
	var field string
	var ok bool
	for _, c := range cols {
		if _, ok = c.(*col.Action); ok {
			continue
		}
		field, err = c.GetColField()
		if err != nil {
			err = fmt.Errorf("获取表头字段失败: %v", err)
			return
		}
		if field != "" {
			fields = append(fields, field)
		}
	}
	return
}

// 获取表头对象
func (t *Table) getColsMap(stateCode any) (colsMap map[string]table.ColInterface, err error) {
	if t.IsSetState() {
		if t.stateColsMap == nil {
			t.handleActionFuns("State", "Cols")
			if err = t.GetError(); err != nil {
				return
			}
			t.stateColsMap = map[any]map[string]table.ColInterface{}
			cols, _ := tableMapStateValue(stateCode, t.stateCols)
			var colField string
			for _, c := range cols {
				colField, err = c.GetColField()
				if err != nil {
					return
				}
				if _, exists := tableMapStateValue(stateCode, t.stateColsMap); !exists {
					t.stateColsMap[stateCode] = map[string]table.ColInterface{}
				}
				t.stateColsMap[stateCode][colField] = c
			}
		}
		colsMap, _ = tableMapStateValue(stateCode, t.stateColsMap)
		return
	} else {
		if t.colsMap == nil {
			t.handleActionFuns("State", "Cols")
			if err = t.GetError(); err != nil {
				return
			}
			t.colsMap = map[string]table.ColInterface{}
			var colField string
			for _, c := range t.cols {
				colField, err = c.GetColField()
				if err != nil {
					return
				}
				t.colsMap[colField] = c
			}
		}
		colsMap = t.colsMap
		return
	}
}

// 获取表头对象
func (t *Table) getCol(stateCode any, colField string) (col table.ColInterface, err error) {
	colsMap, err := t.getColsMap(stateCode)
	if err != nil {
		return
	}
	if _col, ok := colsMap[colField]; ok {
		col = _col
	}
	return
}

// 校验筛选表单字段
func (t *Table) CheckStateFilter(params map[string]any, scene string) (stateCode any, filterDatas map[string]any, err error) {
	if params == nil {
		return
	}
	t.handleActionFuns("State", "Filter")
	if filterRaw, exists := params["filter"]; exists {
		var ok bool
		filterDatas, ok = filterRaw.(map[string]any)
		if !ok {
			err = errors.New("参数filter类型错误")
			return
		}
	}
	// state
	if t.IsSetState() {
		var exists bool
		stateCode, exists = params["state"]
		if !exists {
			err = errors.New("state参数缺失")
			return
		}
		var stateCodeStr string
		stateCodeStr, err = util.ToString(stateCode)
		if err != nil {
			err = fmt.Errorf("filter[state]参数非比较类型！%v", err)
			return
		}
		stateCodeStrs := t.GetStateCodeStrs()
		if !slices.Contains(stateCodeStrs, stateCodeStr) {
			err = errors.New("filter[state]参数错误")
			return
		}
	}

	// filter
	if t.IsSetFilter() {
		var filterFields []form.FieldInterface
		if t.IsSetState() {
			filterFields, _ = tableMapStateValue(stateCode, t.stateFilter)
		} else {
			filterFields = t.filter
		}
		if len(filterFields) > 0 {
			err = t.CheckFormFields(filterDatas, filterFields, scene)
		}
	}
	return
}

// 是否配置有状态栏
func (t *Table) IsSetState() (res bool) {
	t.handleActionFuns("State")
	res = len(t.state) > 0
	return
}

// 获取状态栏的code字符串值切片
func (t *Table) GetStateCodeStrs() []string {
	if t.stateCodeStrs == nil {
		t.handleActionFuns("State")
		t.stateCodeStrs = make([]string, 0, len(t.state))
		for _, state := range t.state {
			stateCodeStr, err := util.ToString(state.Code)
			if err != nil {
				continue
			}
			t.stateCodeStrs = append(t.stateCodeStrs, stateCodeStr)
		}
	}
	return t.stateCodeStrs
}

// 是否启用分页
func (t *Table) IsEnablePage(stateCode any) (res bool) {
	t.handleActionFuns("State", "Page")
	if t.IsSetState() {
		if t.statePage != nil {
			var exists bool
			if res, exists = tableMapStateValue(stateCode, t.statePage); exists {
				return
			}
		}
	}
	res = t.page
	return
}

// 获取指定状态每页条数的选择项
func (t *Table) GetPageSizeOptionsByState(stateCode any) (res []uint) {
	t.handleActionFuns("State", "PageSizeOptions")
	if t.IsSetState() {
		if t.statePageSizeOptions != nil {
			var exists bool
			if res, exists = tableMapStateValue(stateCode, t.statePageSizeOptions); exists {
				return
			}
		}
	}
	res = t.pageSizeOptions
	return
}

// 是否配置有筛选表单字段
func (t *Table) IsSetFilter() (res bool) {
	t.handleActionFuns("State", "Filter")
	if t.IsSetState() {
		res = t.stateFilter != nil
	} else {
		res = len(t.filter) > 0
	}
	return
}

// 是否请求导出items
func (t *Table) IsRequestExportItems() (res bool) {
	return strings.HasPrefix(t.GinContext.Request.UserAgent(), builderconsts.TABLE_EXPORT_USER_AGENT_PREFIX)
}

// 获取指定状态的事件确认表单配置字段
func (t *Table) GetEventCodes(stateCode any, location string) (codes []any) {
	codes = []any{}
	// Toolbar
	if location == builderconsts.TABLE_EVENT_LOCATION_TOOLBAR {
		t.handleActionFuns("State", "Toolbar")
		if t.IsSetState() {
			if t.stateToolbar != nil {
				if toolbarActions, exists := tableMapStateValue(stateCode, t.stateToolbar); exists && len(toolbarActions) > 0 {
					for _, toolbarAction := range toolbarActions {
						if code, err := toolbarAction.GetActionCode(); err == nil {
							codes = append(codes, code)
						}
					}
				}
			}
		} else {
			if len(t.toolbar) > 0 {
				for _, toolbarAction := range t.toolbar {
					if code, err := toolbarAction.GetActionCode(); err == nil {
						codes = append(codes, code)
					}
				}
			}
		}
		return
	}
	// DefaultToolbar
	if location == builderconsts.TABLE_EVENT_LOCATION_DEFAULT_TOOLBAR {
		t.handleActionFuns("State", "DefaultToolbar")
		if t.IsSetState() {
			if t.stateDefaultToolbar != nil {
				for _, toolbarActions := range t.stateDefaultToolbar {
					for _, toolbarAction := range toolbarActions {
						if code, err := toolbarAction.GetActionCode(); err == nil {
							codes = append(codes, code)
						}
					}
				}
			}
		} else {
			if len(t.defaultToolbar) > 0 {
				for _, toolbarAction := range t.defaultToolbar {
					if code, err := toolbarAction.GetActionCode(); err == nil {
						codes = append(codes, code)
					}
				}
			}
		}
		return
	}
	// Cols
	if location == builderconsts.TABLE_EVENT_LOCATION_COLUMN {
		t.handleActionFuns("State", "Cols")
		if t.stateCols != nil {
			if cols, exists := tableMapStateValue(stateCode, t.stateCols); exists {
				for _, cl := range cols {
					if actionCol, ok := cl.(*col.Action); ok {
						for _, actionColOption := range actionCol.Options {
							if code, err := actionColOption.GetActionCode(); err == nil {
								codes = append(codes, code)
							}
						}
					} else if _, ok := cl.(*col.DragSort); ok {
						codes = append(codes, "sort")
					}
				}
			}
		} else {
			if len(t.cols) > 0 {
				for _, cl := range t.cols {
					if actionCol, ok := cl.(*col.Action); ok && len(actionCol.Options) > 0 {
						for _, actionColOption := range actionCol.Options {
							if code, err := actionColOption.GetActionCode(); err == nil {
								codes = append(codes, code)
							}
						}
					} else if _, ok := cl.(*col.DragSort); ok {
						codes = append(codes, "sort")
					}
				}
			}
		}
		return
	}
	return
}

// 获取指定状态的事件确认表单配置字段
func (t *Table) GetConfirmFormFields(stateCode any, location string, eventCode any) (fields []form.FieldInterface) {
	// 过滤操作项
	filterActions := func(actions []builderaction.ActionInterface) (fields []form.FieldInterface) {
		for _, action := range actions {
			actionCode, err := action.GetActionCode()
			if err != nil {
				continue
			}
			if util.EqualTo(eventCode, actionCode) {
				if actionConfirmFormFields, err := action.GetConfirmFormFields(); err == nil {
					fields = actionConfirmFormFields
					return
				}
			}
		}
		return
	}
	// Toolbar
	if location == builderconsts.TABLE_EVENT_LOCATION_TOOLBAR {
		t.handleActionFuns("State", "Toolbar")
		if t.IsSetState() {
			if t.stateToolbar != nil {
				if toolbarActions, exists := tableMapStateValue(stateCode, t.stateToolbar); exists {
					actions := make([]builderaction.ActionInterface, 0, len(toolbarActions))
					for _, toolbarAction := range toolbarActions {
						actions = append(actions, toolbarAction)
					}
					if fields = filterActions(actions); len(fields) > 0 {
						return
					}
				}
			}
		} else {
			if len(t.toolbar) > 0 {
				actions := make([]builderaction.ActionInterface, 0, len(t.toolbar))
				for _, toolbarAction := range t.toolbar {
					actions = append(actions, toolbarAction)
				}
				if fields = filterActions(actions); len(fields) > 0 {
					return
				}
			}
		}
		return
	}
	// DefaultToolbar
	if location == builderconsts.TABLE_EVENT_LOCATION_DEFAULT_TOOLBAR {
		t.handleActionFuns("State", "DefaultToolbar")
		if t.IsSetState() {
			if t.stateDefaultToolbar != nil {
				if toolbarActions, exists := tableMapStateValue(stateCode, t.stateDefaultToolbar); exists {
					actions := make([]builderaction.ActionInterface, 0, len(toolbarActions))
					for _, toolbarAction := range toolbarActions {
						actions = append(actions, toolbarAction)
					}
					if fields = filterActions(actions); len(fields) > 0 {
						return
					}
				}
			}
		} else {
			if len(t.defaultToolbar) > 0 {
				actions := make([]builderaction.ActionInterface, 0, len(t.defaultToolbar))
				for _, toolbarAction := range t.defaultToolbar {
					actions = append(actions, toolbarAction)
				}
				if fields = filterActions(actions); len(fields) > 0 {
					return
				}
			}
		}
		return
	}
	// Cols
	if location == builderconsts.TABLE_EVENT_LOCATION_COLUMN {
		t.handleActionFuns("State", "Cols")
		if t.IsSetState() {
			if t.stateCols != nil {
				if cols, exists := tableMapStateValue(stateCode, t.stateCols); exists {
					for _, cl := range cols {
						if actionCol, ok := cl.(*col.Action); ok && len(actionCol.Options) > 0 {
							actions := make([]builderaction.ActionInterface, 0, len(actionCol.Options))
							for _, actionColOption := range actionCol.Options {
								actions = append(actions, actionColOption)
							}
							if fields = filterActions(actions); len(fields) > 0 {
								return
							}
						}
					}
				}
			}
		} else {
			if len(t.cols) > 0 {
				for _, cl := range t.cols {
					if actionCol, ok := cl.(*col.Action); ok && len(actionCol.Options) > 0 {
						actions := make([]builderaction.ActionInterface, 0, len(actionCol.Options))
						for _, actionColOption := range actionCol.Options {
							actions = append(actions, actionColOption)
						}
						if fields = filterActions(actions); len(fields) > 0 {
							return
						}
					}
				}
			}
		}
		return
	}
	return
}

// 获取指定状态的map状态值数据（预防前端传到后端解析为map后数字类型变味了Float64）
func tableMapStateValue[T any](stateCode any, m map[any]T) (value T, exists bool) {
	// 如果是字符串则直接匹配
	if stateCodeStr, ok := stateCode.(string); ok {
		var res T
		res, exists = m[stateCodeStr]
		if exists {
			value = res
		}
		return
	}
	// 如果不是字符串，则先把stateCode和map的key转换为字符串后再进行比较
	stateCodeStr := fmt.Sprintf("%v", stateCode)
	for k, v := range m {
		if stateCodeStr == fmt.Sprintf("%v", k) {
			value = v
			exists = true
			return
		}
	}
	return
}
